package com.mall;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeSet;

import com.mall.util.DateUtil;

public class Discountor {
	List<Discount> discounts = new ArrayList<Discount>();
	List<Coupons> coupons = new ArrayList<Coupons>(); 
	String now;
	public Discountor addDiscount(AbstractDiscount dis){
		if(dis instanceof Discount){
			discounts.add((Discount) dis);
		}
		if(dis instanceof Coupons){
			coupons.add((Coupons) dis);
		}
		return this;
	}
	public Discountor commitDate(String commitDate){
		this.now = commitDate;
		return this;
	}
	public double discount(ShoppingCart shoppingCart){
		double totalPrice = 0;
		List<CartItem> items = shoppingCart.getItems();
		for(CartItem item:items){
			Goods good  = item.getGoods();
			double price = good.getPrice()*item.getQuantity();
			for(Discount discount:discounts){
				discount.setNow(DateUtil.formatStrToDate(now, DateUtil.DATE_FORMAT_SHORT));
				if(discount.isAvalible()&&discount.getCategory().contains(good.getItem())){
					price = price*discount.getRebate();
				}
			}
			totalPrice = totalPrice+price;
		}
		TreeSet<Coupons> canUseCoupons = new TreeSet<Coupons>();
		for(Coupons coupon:coupons){
			coupon.setNow(DateUtil.formatStrToDate(now, DateUtil.DATE_FORMAT_SHORT));
			if(coupon.isAvalible()&&coupon.getThreshold()<=totalPrice){
				canUseCoupons.add(coupon);
			}
		}
		if(canUseCoupons.size()>0){
			Coupons using = canUseCoupons.first();
			totalPrice = totalPrice-using.getDiscountValue();
			using.setUsed(true);
		}
		return new BigDecimal(totalPrice).setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
	}
}
